package mae.app;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * Class that provides the functionality to query, create, and update Boscul
 * items.
 * 
 * @author DJ
 * 
 */
public class BosculAdapter {
	// Database fields
	public static final String KEY_ROWID = "_id";
	public static String KEY_SIZEOFWRITING = "SizeofWriting";
	public static final String KEY_NAME = "Name";
	public static final String KEY_DESCRIPTION = "Description";
	public static final String KEY_VALUE = "Value";
	public static final String KEY_STATUS = "Status";
	private static final String BOSCUL_TABLE = "Boscul";
	private Context context;
	private SQLiteDatabase db;
	private CollectionsDatabaseHelper dbHelper;
	private String smallWriting = "Small Writing";
	private String largeWriting = "Large Writing";

	public BosculAdapter(Context context) {
		this.context = context;
	}

	public BosculAdapter open() throws SQLException {
		dbHelper = new CollectionsDatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		dbHelper.close();
	}

	/**
	 * Update the Boscul item
	 */
	public boolean updateBoscul(long rowId, String status) {
		ContentValues values = createContentValues(status);
		return db.update(BOSCUL_TABLE, values, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all Boscul with small writing in the
	 * database
	 * 
	 * @return Cursor over all small writing items.
	 */
	public Cursor fetchAllSmallWritingBosculs() {
		return db.query(false, BOSCUL_TABLE, new String[] { KEY_ROWID,
				KEY_NAME, KEY_DESCRIPTION, KEY_VALUE, KEY_STATUS },
				KEY_SIZEOFWRITING + "=" + smallWriting, null, null, null, null,
				null);
	}

	/**
	 * Return a Cursor over the list of all Boscul with large writing in the
	 * database
	 * 
	 * @return Cursor over all large writing items.
	 */
	public Cursor fetchAllLargeWritingBosculs() {
		return db.query(BOSCUL_TABLE, new String[] { KEY_ROWID, KEY_NAME,
				KEY_DESCRIPTION, KEY_VALUE, KEY_STATUS }, KEY_SIZEOFWRITING
				+ "=" + largeWriting, null, null, null, null);
	}

	/**
	 * Return a Cursor positioned at the defined Boscul
	 */
	public Cursor fetchBoscul(long rowId) throws SQLException {
		Cursor mCursor = db.query(BOSCUL_TABLE, new String[] { KEY_NAME,
				KEY_DESCRIPTION, KEY_VALUE, KEY_STATUS }, KEY_ROWID + "="
				+ rowId, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;
	}

	/**
	 * Puts the inputed status into the database
	 * 
	 * @param status
	 * @return
	 */
	private ContentValues createContentValues(String status) {
		ContentValues values = new ContentValues();
		values.put(KEY_STATUS, status);
		return values;
	}
}
